<template>
  <div class="app-manage-page">
    <div class="page-header">
      <h2 class="page-title">应用管理</h2>
      <p class="page-subtitle">管理系统应用信息</p>

      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <a-form layout="inline" :model="searchForm" class="search-form">
          <a-form-item label="应用名称">
            <a-input
              v-model:value="searchForm.appName"
              placeholder="请输入应用名称"
              allow-clear
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="创建者">
            <a-input
              v-model:value="searchForm.userId"
              placeholder="请输入用户ID"
              allow-clear
              style="width: 150px"
            />
          </a-form-item>
          <a-form-item label="优先级">
            <a-select
              v-model:value="searchForm.priority"
              placeholder="请选择优先级"
              allow-clear
              style="width: 150px"
            >
              <a-select-option :value="99">精选应用</a-select-option>
              <a-select-option :value="0">普通应用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset" style="margin-left: 8px"> 重置 </a-button>
          </a-form-item>
        </a-form>
      </div>

      <a-divider />

      <!-- 应用列表 -->
      <div class="table-section">
        <a-table
          :columns="columns"
          :data-source="appList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'appName'">
              <div class="app-name-cell">
                <div class="app-name">{{ record.appName }}</div>
                <div class="app-prompt">{{ record.initPrompt?.substring(0, 50) }}...</div>
              </div>
            </template>

            <template v-else-if="column.key === 'user'">
              <div class="user-cell">
                <a-avatar :src="record.user?.avatar" size="small">
                  {{ record.user?.username?.charAt(0) }}
                </a-avatar>
                <span class="username">{{ record.user?.username }}</span>
              </div>
            </template>

            <template v-else-if="column.key === 'priority'">
              <a-tag v-if="record.priority === 99" color="gold">精选</a-tag>
              <span v-else>{{ record.priority }}</span>
            </template>

            <template v-else-if="column.key === 'deployStatus'">
              <a-tag v-if="record.deployKey" color="green">已部署</a-tag>
              <a-tag v-else color="default">未部署</a-tag>
            </template>

            <template v-else-if="column.key === 'createTime'">
              {{ formatTime(record.createTime) }}
            </template>

            <template v-else-if="column.key === 'action'">
              <div class="action-buttons">
                <a-button type="link" size="small" @click="handleEdit(record)"> 编辑 </a-button>
                <a-button type="link" size="small" @click="handleView(record)"> 查看 </a-button>
                <a-button
                  v-if="record.priority !== 99"
                  type="link"
                  size="small"
                  @click="handleSetFeatured(record)"
                >
                  精选
                </a-button>
                <a-button type="link" size="small" danger @click="handleDelete(record)">
                  删除
                </a-button>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>



    <!-- 删除确认对话框 -->
    <a-modal
      v-model:open="deleteModalVisible"
      title="确认删除"
      @ok="confirmDelete"
      @cancel="cancelDelete"
    >
      <p>确定要删除应用 "{{ selectedApp?.appName }}" 吗？此操作不可恢复。</p>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { deleteAppByAdmin, listAppVoByPageByAdmin, updateAppByAdmin } from '@/api/appController'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const appList = ref<API.AppVO[]>([])
const deleteModalVisible = ref(false)
const selectedApp = ref<API.AppVO | null>(null)

// 搜索表单
const searchForm = reactive({
  appName: '',
  userId: '',
  priority: undefined as number | undefined,
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
})

// 表格列配置
const columns = [
  {
    title: '应用名称',
    key: 'appName',
    width: 300,
  },
  {
    title: '创建者',
    key: 'user',
    width: 150,
  },
  {
    title: '优先级',
    key: 'priority',
    width: 100,
  },
  {
    title: '部署状态',
    key: 'deployStatus',
    width: 100,
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 方法
const loadAppList = async () => {
  loading.value = true
  try {
    const params: API.AppQueryRequest = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      appName: searchForm.appName || undefined,
      userId: searchForm.userId ? Number(searchForm.userId) : undefined,
      priority: searchForm.priority,
    }

    const res = await listAppVoByPageByAdmin(params)
    if (res.code === 0 && res.data) {
      appList.value = res.data.records || []
      pagination.total = Number(res.data.total) || 0
    } else {
      message.error(res.message || '加载应用列表失败')
    }
  } catch (error) {
    message.error('加载应用列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadAppList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    appName: '',
    userId: '',
    priority: undefined,
  })
  pagination.current = 1
  loadAppList()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadAppList()
}

const handleEdit = (record: API.AppVO) => {
  if (record.id) {
    router.push(`/app/edit/${record.id}`)
  }
}

const handleView = (record: API.AppVO) => {
  if (record.id) {
    router.push(`/app/chat/${record.id}`)
  }
}

const handleSetFeatured = async (record: API.AppVO) => {
  try {
    const res = await updateAppByAdmin({
      id: record.id,
      priority: 99,
    })
    if (res.code === 0) {
      message.success('设置精选成功')
      loadAppList()
    } else {
      message.error(res.message || '设置精选失败')
    }
  } catch (error) {
    message.error('设置精选失败')
    console.error(error)
  }
}

const handleDelete = (record: API.AppVO) => {
  selectedApp.value = record
  deleteModalVisible.value = true
}

const confirmDelete = async () => {
  if (!selectedApp.value?.id) return

  try {
    const res = await deleteAppByAdmin({ id: selectedApp.value.id })
    if (res.code === 0) {
      message.success('删除成功')
      deleteModalVisible.value = false
      selectedApp.value = null
      loadAppList()
    } else {
      message.error(res.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
    console.error(error)
  }
}

const cancelDelete = () => {
  deleteModalVisible.value = false
  selectedApp.value = null
}

const formatTime = (timeStr?: string) => {
  if (!timeStr) return '未知时间'
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadAppList()
})
</script>

<style scoped>
.app-manage-page {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}



.search-section {
  padding: 16px 16px 0 0;
  margin-bottom: 8px;
}

.search-form {
  margin: 0;
}

.table-section {
  overflow: hidden;
}

.app-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.app-name {
  font-weight: 500;
  color: #333;
}

.app-prompt {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-size: 14px;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .ant-btn {
  padding: 0;
  height: auto;
  line-height: 1;
}

@media (max-width: 768px) {
  .app-manage-page {
    padding: 16px;
  }

  .search-section,
  .table-section {
    padding: 16px;
  }

  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-form .ant-form-item {
    margin-bottom: 16px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
